package me.feng.servlet

import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import me.feng.db.DbHelper
import javax.servlet.annotation.WebServlet
import me.feng.domain.Member
import me.feng.entity.Message
import me.feng.entity.MessageType
import me.feng.entity.Event
import me.feng.entity.User
import me.feng.actors.MainActor
import me.feng.entity.EventType
import me.feng.util.JsonUtil
import com.lambdaworks.jacks.JacksMapper
import javax.servlet.http.Cookie

@WebServlet(Array("/auth.do"))
class AuthServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    val username = req.getParameter("username")
    val password = req.getParameter("password")
    val m = Member.getMemberbyUsername(username)
    val msg = if (m != null && m.password.equals(password)) {
      val c = new Cookie("sid",req.getSession().getId())
      c.setPath("/")
      resp.addCookie(c)
      new Message(MessageType.EVENT, new Event(User.member2User(m), MainActor.DEFAULT_MAIN_ID, EventType.LOGIN_SUCCESS))
    } else {
      new Message(MessageType.EVENT, new Event(null, MainActor.DEFAULT_MAIN_ID, EventType.LOGIN_FAILE))
    }
    val result = JacksMapper.writeValueAsString(msg)
    
    resp.setCharacterEncoding("UTF-8")
    resp.setContentType("application/x-javascript;charset=UTF-8");
    val out = resp.getWriter()
    out.print(result)
    out.close()
  }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) {
    doGet(req, resp)
  }
}